<?php

/**
 *Simple CRUD Code Generator
 *Email:  support@crazedcoders.com
 *Website: http://www.crazedcoders.com/
 *Copyright (C) 2007 CrazedCoders
 *
 *This program is free software: you can redistribute it and/or modify
 *it under the terms of the GNU General Public License as published by
 *the Free Software Foundation, either version 3 of the License, or
 *(at your option) any later version.
 *
 *THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *SOFTWARE.
 *
 *You should have received a copy of the GNU General Public License
 *along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * generates a view for a given table
 */
function generateTestForTable( $table ) {
	$assoc = $table[0][2];
	$className = toCamelCase( $assoc['table_name'] );
	$classNameUp = strtoupper( $className );
	$classNameLow = strtolower( $className );
	$tableName = $assoc['table_name'];
	$refManyTables = findRefManyColumnsFromTable( $table );
	//for( $k = 0; $k < sizeof( $table ); $k++ ) {
	foreach( $table as $k=>$value ) {
		if( ! is_int( $k ) ) {
			continue;
		}
		if( array_key_exists(2, $table[$k] )
			   && $table[$k][2]['constraint_type'] == 'PRIMARY KEY' ) {
			$assoc = $table[$k][2];
			$primaryKey = toCamelCaseMember($table[$k][2]['column_name']);
		}
	}
	//$columns = getTableColumns( $tableName );
	$columns = $table;
	$columnsString = join(', ',array_keys($columns));
	$secondaryKeys = array();
	foreach( $columns as $key=>$value ) {
		$secondaryKeys[$key] = $columns[$key];
	}
	//$secondaryKeys = StdFunc::array_clone( $columns );
	unset( $secondaryKeys[$primaryKey] );

	$export =
'<?xml version="1.0" encoding="utf-8"?>
<!--

 Simple CRUD Code Generator
 Email:  support@crazedcoders.com
 Website: http://www.crazedcoders.com/
 Copyright (C) 2007 CrazedCoders

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

-->
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
	xmlns:control="com.crazedcoders.lib.control.*"
	implements="com.crazedcoders.lib.interfaces.IView"
	label="'.$className.'"
	initialize="initValidators()">
<mx:Metadata>
	[Event("statusUpdate","flash.events.DataEvent")]
</mx:Metadata>
<mx:Script>
	<![CDATA[
		import '.con::$package.'.model.AppModel;
		import mx.events.ValidationResultEvent;
		import com.adobe.cairngorm.model.ModelLocator;
		import com.adobe.cairngorm.control.CairngormEventDispatcher;
		import mx.rpc.events.ResultEvent;
		import '.con::$package.'.event.'.$className.'Event;
		import mx.utils.ObjectUtil;
		import mx.controls.Alert;
        import mx.validators.Validator;
		import mx.rpc.events.FaultEvent;
		import mx.rpc.events.ResultEvent;
		import mx.rpc.events.AbstractEvent;
		import '.con::$package.'.vo.'.$className.';
		/*
		 * '.$className.' Cairngorm test view
		 */

		[Bindable]
		private var model:AppModel = AppModel.getInstance();
		[Bindable]
		public var title:String = "Test '.$className.' Remote Calls";
		[Bindable]
		public var currentItem:'.$className.';
		[Bindable]
		public var newRecord:Boolean = false;
		private var formValidators:Array;

';
/*
		private function onUpdate( event:CommandEvent):void {
			//Alert.show( ResultEvent(event.serviceEvent).result.toString() );
			switch( event.originalEvent.type ) {
				case '.$className.'Event.'.$classNameUp.'_ACTION_COUNT_ALL:
					this.countAllTextInput.text =
						this.model.'.$classNameLow.'Count.toString();
					break;
				case '.$className.'Event.'.$classNameUp.'_ACTION_GET_ALL:
					//this.testDataGrid.dataProvider =
					//	this.'.$classNameLow.'Model.array;
					break;
				case '.$className.'Event.'.$classNameUp.'_ACTION_GET_ALL_BY_START_LENGTH:
					//this.testDataGrid.dataProvider =
					//	this.'.$classNameLow.'Model.array;
					break;
			}
			// text="{this.'.$classNameLow.'Model.count}"
		}
*/

	$export .=
'
		private function initValidators():void{
			formValidators = [VALIDATOR_ARRAY];
		}

		private function cg_countAll():void {
			var ev:'.$className.'Event = new '.$className.'Event(
				'.$className.'Event.'.$classNameUp.'_ACTION_COUNT_ALL, this );
			//CairngormEventDispatcher.getInstance().dispatchEvent( ev );
			ev.dispatch();
		}

		private function cg_getAll():void {
			var ev:'.$className.'Event = new '.$className.'Event(
				'.$className.'Event.'.$classNameUp.'_ACTION_GET_ALL, this );
			//CairngormEventDispatcher.getInstance().dispatchEvent( ev );
			ev.dispatch();
		}

		private function cg_getAllStartLength():void {
			var ev:'.$className.'Event = new '.$className.'Event(
				'.$className.'Event.'.$classNameUp.'_ACTION_GET_ALL_BY_START_LENGTH, this );
			ev.paramStart = int(paramStart.text);
			ev.paramLength = int(paremLength.text);
			//CairngormEventDispatcher.getInstance().dispatchEvent( ev );
			ev.dispatch();
		}

		public function update(originalEvent:Event, serviceEvent:AbstractEvent = null):void{
			if (serviceEvent is ResultEvent)
				switch (originalEvent.type){
					//update view as needed based on command
					default:
						dispatchEvent(new DataEvent(
							"statusUpdate",false,false,originalEvent.type + " completed!"));
				}
			else
				Alert.show(FaultEvent(serviceEvent).fault.faultDetail);
		}

		private function genOne'.$className.'():'.$className.' {
			return( '.$className.'.construct(
';

		$firstFlag = false;
		//echo " \$className = $className <br />";
		foreach( $columns as $k=>$column ) {
			if( ! is_int( $k ) ) {
				continue;
			}
			//echo "\n\n";
			$key = $column[0];
			$value = $column[1];
			$fkeyname = toFKeyName( $key );
				$isFkey =
						array_key_exists(2, $column)
					   	&& $column[2]['constraint_type'] == 'FOREIGN KEY'
						&& $fkeyname;
			if( ! $isFkey ) {
				if ( substr_count( strtolower($value), 'bit' ) > 0 ||
						substr_count( strtolower($value), 'tinyint' ) > 0  ) {
					//echo "type detected: bit <br />";
					$export .=
'				'.($firstFlag?',':'').'currentItem.'.toCamelCaseMember($key).'
';
				}
				else if( substr_count( strtolower($value), 'int' ) > 0 ) {
					//echo "type detected: int <br />";
					$export .=
'				'.($firstFlag?',':'').'currentItem.'.toCamelCaseMember($key).'
';
				}
				else {
					//echo "type detected: other($value)\n";
					$export .=
'				'.($firstFlag?',':'').'currentItem.'.toCamelCaseMember($key).'
';
				}
			}
			else {
					$export .=
'				'.($firstFlag?',':'').'currentItem!=null?currentItem.'.$fkeyname.':null
';
			}
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}

		foreach( $refManyTables as $k=>$refManyColumn ) {
			if( ! is_int( $k ) ) {
				continue;
			}
			$refTableName =
				toCamelCaseMember(
						$refManyColumn['away_column'][2]['referenced_table_name']);
			$export .=
'				'.($firstFlag?',':'').'null
';
			$firstFlag = true;
		}

		$export .=
'				));
		}

		private function cg_createOne():void {
			if(newRecord){
				if(Validator.validateAll(formValidators).length == 0)
				{
					var ev:'.$className.'Event = new '.$className.'Event(
						'.$className.'Event.'.$classNameUp.'_ACTION_CREATE_ONE, this);
					ev.paramItem = this.genOne'.$className.'();
					ev.dispatch();
					currentItem = '.$className.'(testDataGrid.selectedItem);
					newRecord = false;
				}
			}
		}

		private function cg_updateOne():void {
			if(Validator.validateAll(formValidators).length == 0)
				{
				var ev:'.$className.'Event = new '.$className.'Event(
					'.$className.'Event.'.$classNameUp.'_ACTION_UPDATE_ONE, this);
				ev.paramItem =
					//this.genOne'.$className.'();
					(this.testDataGrid.selectedItem as '.$className.');
				ev.dispatch();
				}
		}

		private function cg_deleteOne():void {
			var ev:'.$className.'Event = new '.$className.'Event(
				'.$className.'Event.'.$classNameUp.'_ACTION_DELETE_ONE, this);
			ev.paramItem =
				//this.genOne'.$className.'();
				(this.testDataGrid.selectedItem as '.$className.');
			ev.dispatch();
		}

		private function newOne():void{
			currentItem = new '.$className.';
			newRecord = true;
		}

		private function cancelNewOne():void{
			currentItem = '.$className.'(testDataGrid.selectedItem);
			newRecord = false;
		}
';
	if( isset ($primaryKey) ) {
	$export .=
'

		private function cg_getOne():void {
			var ev:'.$className.'Event = new '.$className.'Event(
				'.$className.'Event.'.$classNameUp.'_ACTION_GET_ONE, this);
			if(numV.validate().type == ValidationResultEvent.VALID){
				ev.paramPrimaryKey = int(this.paramPrimaryKey.text); //this.genOne'.$className.'();
				ev.dispatch();
			}
		}
';
	}
	$export .=
'
	]]>
</mx:Script>
';
/*<control:ViewController
	eventFilter="{[ '.$className.'Event.'.$classNameUp.'_ACTION_COUNT_ALL,
					'.$className.'Event.'.$classNameUp.'_ACTION_GET_ONE,
					'.$className.'Event.'.$classNameUp.'_ACTION_GET_ALL,
					'.$className.'Event.'.$classNameUp.'_ACTION_GET_ALL_BY_START_LENGTH,
					'.$className.'Event.'.$classNameUp.'_ACTION_CREATE_ONE,
					'.$className.'Event.'.$classNameUp.'_ACTION_UPDATE_ONE,
					'.$className.'Event.'.$classNameUp.'_ACTION_DELETE_ONE  ]}"
	updated="onUpdate(event)" />
*/
	$export .=
'
<mx:NumberValidator id="numV" required="true"
     source="{paramPrimaryKey}" property="text"
     minValue="1" domain="int"/>
<mx:ButtonBar x="10" y="5"
	direction="vertical" dataProvider="vs1" width="100"/>
<mx:VDividedBox left="120" top="0" bottom="0" right="0">
<mx:ViewStack id="vs1" width="100%" height="60%">
';

	$bindings = '';
	$validators = '';
	$validatorIdentifiers = '';
	$export .=
'
	<mx:Panel title="Create/Update/Delete" label="CRUD Actions"
		verticalScrollPolicy="auto" minHeight="280" width="100%"
		horizontalScrollPolicy="off">
		<mx:Form width="100%" height="100%"
			enabled="{newRecord == true || testDataGrid.selectedItem != null}"
			verticalScrollPolicy="off"
			horizontalScrollPolicy="off">
';
		$firstFlag = false;
		foreach( $columns as $k=>$column ) {
			if( ! is_int( $k ) ) {
				continue;
			}
			$key = $column[0];
			$value = $column[1];
			$fkeyname = toFKeyName( $key );
				$isFkey =
						array_key_exists(2, $column)
					   	&& $column[2]['constraint_type'] == 'FOREIGN KEY'
						&& $fkeyname;
			if( ! $isFkey ) {
				if ( substr_count( strtolower($value), 'bit' ) > 0  ||
						substr_count( strtolower($value), 'tinyint' ) > 0  ) {
					$export .=
'
			<mx:FormItem label="'.toCamelCaseMember($key).' (Boolean)">
				<mx:CheckBox id="input_'.toCamelCaseMember($key).'"
					selected="{currentItem.'.toCamelCaseMember($key).'}"
					/>
			</mx:FormItem>
';
				$bindings .= '<mx:Binding source="input_'.toCamelCaseMember($key).'.selected" destination="currentItem.'.toCamelCaseMember($key).'"/>
';
				}				
				else if( substr_count( strtolower($value), 'int' ) > 0 ) {
					$export .=
'
			<mx:FormItem label="'.toCamelCaseMember($key).' (int)">
				<mx:TextInput id="input_'.toCamelCaseMember($key).'"
					text="{currentItem.'.toCamelCaseMember($key).'}"
					/>
			</mx:FormItem>
';
				$bindings .= '<mx:Binding source="int(input_'.toCamelCaseMember($key).'.text)" destination="currentItem.'.toCamelCaseMember($key).'"/>
';
				$validators .='<mx:NumberValidator id="validate_'.toCamelCaseMember($key).'" source="{input_'.toCamelCaseMember($key).'}" property="text" domain="int"/>
';
				$validatorIdentifiers .= ($firstFlag?', ':'').'validate_'.toCamelCaseMember($key);
				}
				else if ( substr_count( strtolower($value), 'date' ) > 0  ) {
					$export .=
'
			<mx:FormItem label="'.toCamelCaseMember($key).' (Date)">
				<mx:DateField id="input_'.toCamelCaseMember($key).'" width="150"
					selectedDate="{currentItem.'.toCamelCaseMember($key).'}"
					/>
			</mx:FormItem>
';
				$bindings .= '<mx:Binding source="input_'.toCamelCaseMember($key).'.selectedDate" destination="currentItem.'.toCamelCaseMember($key).'"/>
';
				$validators .='<mx:DateValidator id="validate_'.toCamelCaseMember($key).'" source="{input_'.toCamelCaseMember($key).'}" property="text"  />
';
				$validatorIdentifiers .= ($firstFlag?', ':'').'validate_'.toCamelCaseMember($key);
				}
				else if ( substr_count( strtolower($value), 'decimal' ) > 0
							||  substr_count( strtolower($value), 'double' ) > 0
							||  substr_count( strtolower($value), 'float'  ) > 0
							||  substr_count( strtolower($value), 'real'  ) > 0
							||  substr_count( strtolower($value), 'numeric'  ) > 0   ) {
					$export .=
'
			<mx:FormItem label="'.toCamelCaseMember($key).' (Number)">
				<mx:TextInput id="input_'.toCamelCaseMember($key).'"
					text="{currentItem.'.toCamelCaseMember($key).'}"
					/>
			</mx:FormItem>
';
				$bindings .= '<mx:Binding source="Number(input_'.toCamelCaseMember($key).'.text)" destination="currentItem.'.toCamelCaseMember($key).'"/>
';
				$validators .='<mx:NumberValidator id="validate_'.toCamelCaseMember($key).'" source="{input_'.toCamelCaseMember($key).'}" property="text" domain="real"/>
';
				$validatorIdentifiers .= ($firstFlag?', ':'').'validate_'.toCamelCaseMember($key);
				}
				else if ( substr_count( strtolower($value), 'char' ) > 0
							||  substr_count( strtolower($value), 'text' ) > 0
							||  substr_count( strtolower($value), 'time'  ) > 0 ){
					$export .=
'
			<mx:FormItem label="'.toCamelCaseMember($key).' (String)">
				<mx:TextInput id="input_'.toCamelCaseMember($key).'"
					text="{currentItem.'.toCamelCaseMember($key).'}"
					/>
			</mx:FormItem>
';
				$bindings .= '<mx:Binding source="input_'.toCamelCaseMember($key).'.text" destination="currentItem.'.toCamelCaseMember($key).'"/>
';
				}
				else {
						// Ignore all other column types.
					}
			}
			else {
				$refClassname = toCamelCase( $column[2]
						['referenced_table_name'] );
				$refPKey = getPKey( con::$tables[$column[2]
						['referenced_table_name']] );
				$validators .= "";//TODO: need to set these up yet
				$bindings .= "";
				$export .=
'
			<mx:FormItem label="'.$fkeyname.' ('.$refClassname.')">
				<mx:ComboBox id="input_'.$fkeyname.'"
					prompt="Click to Select"
					dataProvider="{model.'.toCamelCaseMember($refClassname).'s}"
					labelField="name"
					change="currentItem.'.$fkeyname.' =
						'.con::$package.'.vo.'.$refClassname.'(input_'.$fkeyname.'.selectedItem)"
					selectedItem="{currentItem.'.$fkeyname.'}"
					enabled="{currentItem != null}"
					/>
			</mx:FormItem>
';

			}
			if( ! $firstFlag ) {
				$firstFlag = true;
			}

		}
		$export .=
'
		</mx:Form>
		<mx:ControlBar>
			<mx:Button label="New" click="newOne()"
				visible="{!newRecord}"
				includeInLayout="{!newRecord}"/>
			<mx:Button label="Cancel" click="cancelNewOne()"
				visible="{newRecord}"
				includeInLayout="{newRecord}"/>
			<mx:Button label="Save" click="cg_createOne()"
				visible="{newRecord}"
				includeInLayout="{newRecord}"/>
			<mx:Button label="Update Selected" click="cg_updateOne()"
				enabled="{testDataGrid.selectedItem != null}"
				 visible="{!newRecord}"
				 includeInLayout="{!newRecord}"/>
			<mx:Button label="Delete Selected" click="cg_deleteOne()"
				enabled="{testDataGrid.selectedItem != null}"
				visible="{!newRecord}"
				includeInLayout="{!newRecord}"/>
		</mx:ControlBar>
	</mx:Panel>

	<mx:Panel title="Get Record Count" label="Record Count"
		verticalScrollPolicy="off"
		horizontalScrollPolicy="off">
		<mx:Form width="100%">
			<mx:FormItem label="Count:" direction="horizontal">
				<mx:Button label="Get Count"
					click="cg_countAll()" />
				<mx:TextInput id="countAllTextInput"
					text="{model.'.toCamelCaseMember($className).'Count}"
					enabled="false" />
			</mx:FormItem>
		</mx:Form>
	</mx:Panel>
';
	if( isset ( $primaryKey ) ) {
	$export .=
'
	<mx:Panel  title="getOne" label="Get One Record">
		<mx:Form width="100%" height="100%">
			<mx:FormItem label="'.$primaryKey.'" direction="horizontal">
				<mx:TextInput id="paramPrimaryKey"
					text="{currentItem.'.toCamelCaseMember($primaryKey).'}"/>
				<mx:Button label="getOne" click="cg_getOne()" />
			</mx:FormItem>
		</mx:Form>
	</mx:Panel>
';
}
	$export .=
'</mx:ViewStack>
	<mx:Panel title="Records List"
		verticalScrollPolicy="auto" width="100%" height="50%"
		horizontalScrollPolicy="off">
		<mx:DataGrid
			width="100%" height="100%"
			id="testDataGrid"
			dataProvider="{this.model.'.toCamelCaseMember($className).'s}"
			change="{currentItem = '.$className.'(testDataGrid.selectedItem);newRecord=false}">
			<mx:columns>
';
		foreach( $columns as $k=>$column ) {
			if( ! is_int( $k ) ) {
				continue;
			}
			$key = $column[0];
			$value = $column[1];
			$fkeyname = toFKeyName( $key );
				$isFkey =
						array_key_exists(2, $column)
					   	&& $column[2]['constraint_type'] == 'FOREIGN KEY'
						&& $fkeyname;
			if( ! $isFkey ) {
				$export .=
'					<mx:DataGridColumn headerText="'.toCamelCaseMember($key).'" dataField="'.toCamelCaseMember($key).'"/>
';
			}
		}
	$export .=
'			</mx:columns>
		</mx:DataGrid>
		<mx:ControlBar>
			<mx:Button label="getAll" click="cg_getAll()" />
			<mx:Spacer width="100%" />
			<mx:TextInput id="paramStart" text="1" />
			<mx:TextInput id="paremLength" text="5" />
			<mx:Button label="getAllByStartLength" click="cg_getAllStartLength()" />
		</mx:ControlBar>
	</mx:Panel>
</mx:VDividedBox>
';
		$export .= '<!-- Data Validators -->
'.$validators.'
';
		$export .= '<!-- Bindings -->
'.$bindings.'
</mx:Canvas>
';
		$export = str_replace('VALIDATOR_ARRAY' , $validatorIdentifiers, $export);
		return $export;

}

?>
